package model

import (
	"errors"
	"ginblog/tools/pagination"
	"ginblog/utils/errmsg"
	"gorm.io/gorm"
)

type Category struct {
	BaseModel
	CategoryName string `gorm:"type:varchar(20);not null;comment:'分类名称'" json:"category_name"`
}

// SelectAllCat /查询所有分类
func (c *Category) SelectAllCat(page *pagination.Pagination) {
	var categoryList []Category
	err := Db.Select("id", "category_name").Limit(page.GetPageSize()).Offset(page.GetOffset()).Find(&categoryList).Count(&page.Total).Error
	if err != nil {
		c.SteCodeMsg(errmsg.ERROR)
	}
	page.SetTotalPage()
	page.Data = categoryList
}

// AddCat /保存分类
func (c *Category) AddCat() bool {
	err := Db.Create(&c).Error
	if err != nil {
		return false
	}
	return true
}

// EditCat /编辑分类
func (c *Category) EditCat() bool {
	err := Db.Model(&c).Where("id = ? ", c.ID).Omit("Id").Updates(c).Error
	if err != nil {
		return false
	}
	return true
}

// DelCat /删除分类
func (c *Category) DelCat() bool {
	err := Db.Delete(&Category{}, c.ID).Error
	if err != nil {
		return false
	}
	return true
}

func (c *Category) IsCategoryNameRepeat() bool {
	category := Category{}
	result := Db.Where(Category{CategoryName: c.CategoryName}).Find(&category)
	if result.RowsAffected > 0 {
		return true
	}
	return false
}

func (c *Category) BeforeCreate(tx *gorm.DB) (err error) {
	if c.CategoryName != "" && c.IsCategoryNameRepeat() {
		err = errors.New(errmsg.GetErrMsg(errmsg.ARTICLE_NAME_IS_USE))
		c.SteCodeMsg(errmsg.ARTICLE_NAME_IS_USE)
	}
	return
}

func (c *Category) BeforeSave(tx *gorm.DB) (err error) {
	if c.CategoryName != "" && c.IsCategoryNameRepeat() {
		err = errors.New(errmsg.GetErrMsg(errmsg.ARTICLE_NAME_IS_USE))
		c.SteCodeMsg(errmsg.ARTICLE_NAME_IS_USE)
	}
	return
}
